package com.cenwangkeji.resident.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.cenwangkeji.resident.R;
import com.cenwangkeji.resident.model.Constant;
import com.cenwangkeji.resident.model.OkHttpUtils;
import com.cenwangkeji.resident.model.bean.MessageHistoryBean;
import com.cenwangkeji.resident.model.bean.User;
import com.cenwangkeji.resident.ui.adapter.MessageAdapterr;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lws.basic.base.BaseActivity;
import com.lws.basic.persenter.ObserverOnNext;
import com.lws.basic.utils.common.MyLogger;
import com.lws.basic.utils.common.MyToast;
import com.lws.basic.utils.common.RxUtils;
import com.lws.basic.view.adapter.AdapterIntegerDefault0;
import com.lws.basic.view.adapter.DoubleDefault0Adapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;

public class MessageActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener {


    @BindView(R.id.rv)
    RecyclerView mRv;
    private MessageAdapterr mAdapter;
    @BindView(R.id.srl)
    SmartRefreshLayout mSrl;
    private int mId;
    private int mOffset = 0;
    private int mLimit = 10;

    @Override
    public int setLayoutId() {
        return R.layout.activity_message;
    }



    @Override
    public void initData() {
        super.initData();
        ButterKnife.bind(this);
        initRecyclerView();
        initRefresh();
        getData();
    }


    private void initRecyclerView(){
        mRv.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new MessageAdapterr(null);
        mAdapter.setOnItemClickListener(this);
        mRv.setAdapter(mAdapter);
    }

    private void initRefresh() {
        mSrl.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getData();
            }
        });
        mSrl.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                loadmore();
            }
        });
    }

    private void loadmore() {
        showLoading();
        mOffset += 10;
        Observable.create(new ObservableOnSubscribe<MessageHistoryBean>() {
            @Override
            public void subscribe(ObservableEmitter<MessageHistoryBean> emitter) throws Exception {
                Map<Object, Object> map = new HashMap<>();
                map.put("token", User.getToken());
                map.put("mark", 3);
                map.put("offset", mOffset);
                map.put("limit", mLimit);
                map.put("jmId", User.getUserId());
                map.put("ysId", User.getDoctorId());
                JSONObject jsonObject = new JSONObject(map);
                MyLogger.i(jsonObject.toString());
                Gson gson = new GsonBuilder()
                        .registerTypeAdapter(Integer.class, new AdapterIntegerDefault0())
                        .registerTypeAdapter(int.class, new AdapterIntegerDefault0())
                        .registerTypeAdapter(Double.class, new DoubleDefault0Adapter())
                        .registerTypeAdapter(double.class, new DoubleDefault0Adapter())
                        .create();
                String json = OkHttpUtils.post( jsonObject.toString(), Constant.message);
                MyLogger.i(json);
                emitter.onNext(gson.fromJson(json, MessageHistoryBean.class));
            }
        }).compose(RxUtils.<MessageHistoryBean>io_main()).subscribe(new ObserverOnNext<MessageHistoryBean>() {
            @Override
            public void onNext(MessageHistoryBean bean) {
                if (bean.getMsg().equals("Token已过期")) {
                    startActivity(new Intent(MessageActivity.this, LoginActivity.class));

                } else {
                    if (bean.getData() != null && bean.getData().getRows().size() > 0) {
                        mAdapter.addData(bean.getData().getRows());
                    } else {
                        View emptyView = getLayoutInflater().inflate(R.layout.view_empty, null);
                        mAdapter.setEmptyView(emptyView);
                        MyToast.show("没有消息记录");
                    }
                }
                mSrl.finishLoadmore();
                dismissLoading();
            }
        });
    }



    private void getData() {
        showLoading();
        mOffset = 0;
        mLimit = 10;
        Observable.create(new ObservableOnSubscribe<MessageHistoryBean>() {
            @Override
            public void subscribe(ObservableEmitter<MessageHistoryBean> emitter) throws Exception {
                Map<Object, Object> map = new HashMap<>();
                map.put("token", User.getToken());
                map.put("mark", 3);
                map.put("offset", mOffset);
                map.put("limit", mLimit);
                map.put("jmId", User.getUserId());
                map.put("ysId", User.getDoctorId());
                JSONObject jsonObject = new JSONObject(map);
                MyLogger.i(jsonObject.toString());
                Gson gson = new GsonBuilder()
                        .registerTypeAdapter(Integer.class, new AdapterIntegerDefault0())
                        .registerTypeAdapter(int.class, new AdapterIntegerDefault0())
                        .registerTypeAdapter(Double.class, new DoubleDefault0Adapter())
                        .registerTypeAdapter(double.class, new DoubleDefault0Adapter())
                        .create();
                String json = OkHttpUtils.post( jsonObject.toString(), Constant.message);
                MyLogger.i(json);
                emitter.onNext(gson.fromJson(json, MessageHistoryBean.class));

            }
        }).compose(RxUtils.<MessageHistoryBean>io_main()).subscribe(new ObserverOnNext<MessageHistoryBean>() {
            @Override
            public void onNext(MessageHistoryBean bean) {
                if (bean.getMsg().equals("Token已过期")) {
                    startActivity(new Intent(MessageActivity.this, LoginActivity.class));
                    finish();
                } else {
                    if (bean.getData() != null && bean.getData().getRows().size() > 0) {
                        mAdapter.setNewData(bean.getData().getRows());
                    } else {
                        View emptyView = getLayoutInflater().inflate(R.layout.view_empty, null);
                        mAdapter.setEmptyView(emptyView);
                        mAdapter.setNewData(null);
                        MyToast.show("没有消息记录");
                    }
                }
                dismissLoading();
                mSrl.finishRefresh();
            }
        });


    }


    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        MessageHistoryBean.DataBean.RowsBean bean = mAdapter.getData().get(position);
        Intent intent  =new Intent(this,MessageDetailActivity.class);
        intent.putExtra("msg", bean);
        startActivity(intent);
    }
}
